document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const articleId = urlParams.get('id');
    const currentUser = localStorage.getItem('username'); // 假设登录时保存了用户名

    if (articleId) {
        fetchArticleDetails(articleId);
        fetchComments(articleId, 1, 10, currentUser); // 默认加载第一页，10条评论
    }

    const commentForm = document.getElementById('comment-form');
    commentForm.addEventListener('submit', function(event) {
        event.preventDefault();
        const content = document.getElementById('comment-content').value;
        submitComment(articleId, content);
    });
});

function fetchArticleDetails(id) {
    let md = window.markdownit();
    fetch(`/blog/text/listText/${id}`)
        .then(response => response.json())
        .then(data => {
            const articleDiv = document.getElementById('article');
            if (data.code === 1) {
                const article = data.data;
                const htmlContent = md.render(article.content); // text => markdown
                articleDiv.innerHTML = `
                <h2>${article.title}</h2>
                ${htmlContent}
                <small>作者：${article.username} 分类：${article.type} 时间：${new Date(article.createTime).toLocaleString()}</small>
            `;
            } else {
                articleDiv.innerHTML = `<p>加载失败：${data.msg}</p>`;
            }
        })
        .catch(error => {
            const articleDiv = document.getElementById('article');
            articleDiv.innerHTML = `<p>请求失败：${error.message}</p>`;
        });
}

function submitComment(articleId, content) {
    content = encodeURIComponent(content);
    fetch(`/blog/user/submit?id=${articleId}&content=${content}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ id: articleId, content })
    })
        .then(response => response.json())
        .then(data => {
            const commentResponse = document.getElementById('comment-response');
            if (data.code === 1) {
                commentResponse.innerHTML = `<p>评论提交成功</p>`;
                document.getElementById('comment-content').value = ''; // 清空评论框
                fetchComments(articleId, 1, 10, localStorage.getItem('username')); // 重新加载评论
            } else {
                commentResponse.innerHTML = `<p>评论提交失败：${data.msg}</p>`;
            }
        })
        .catch(error => {
            const commentResponse = document.getElementById('comment-response');
            commentResponse.innerHTML = `<p>请求失败：${error.message}</p>`;
        });
}

function fetchComments(articleId, page, pageSize, currentUser) {
    let md = window.markdownit();
    fetch(`/blog/text/listComment?page=${page}&pageSize=${pageSize}&textId=${articleId}`)
        .then(response => response.json())
        .then(data => {
            const commentsDiv = document.getElementById('comments');
            if (data.code === 1) {
                const comments = data.data.records.map(record => {
                    const isCurrentUserComment = record.username === currentUser;
                    const htmlContent = md.render(record.content); // text => markdown
                    return `
                    <div>
                        ${htmlContent}
                        <small>评论者：${record.username} 时间：${new Date(record.createTime).toLocaleString()}</small>
                        ${isCurrentUserComment ? `<button onclick="deleteComment(${record.id})">删除</button>` : ''}
                    </div>
                `;
                }).join('');
                commentsDiv.innerHTML = comments;
            } else {
                commentsDiv.innerHTML = `<p>加载失败：${data.msg}</p>`;
            }
        })
        .catch(error => {
            const commentsDiv = document.getElementById('comments');
            commentsDiv.innerHTML = `<p>请求失败：${error.message}</p>`;
        });
}

function deleteComment(commentId) {
    if (confirm('确定要删除这条评论吗？')) {
        fetch(`/blog/user/deleteComment/${commentId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1) {
                    alert('成功删除评论');
                    const urlParams = new URLSearchParams(window.location.search);
                    const articleId = urlParams.get('id');
                    fetchComments(articleId, 1, 10, localStorage.getItem('username')); // 重新加载评论
                } else {
                    alert('删除评论失败：' + data.msg);
                }
            })
            .catch(error => {
                alert('请求失败：' + error.message);
            });
    }
}
